﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LinkCard.Dao;
using LinkCard.Model;
using LinkCard.AdminCP.Common;

namespace LinkCard.AdminCP.Configuration
{
    public partial class edit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["USER"] == null) { Response.Redirect("/login.aspx"); }
            else
            {
                if (hash1way.CheckPermission(hash1way.GetPermission(Session["USER"].ToString()), "SYSADMIN") == false)
                {
                        Response.Redirect("/message_box.aspx?why=1&msg=5");
                }
            }
            if (!IsPostBack)
            {
                LoadConfig();
            }
        }

        protected void LoadConfig()
        {
            try
            {
                TopLinkEntities db = new TopLinkEntities();
                var configDb = db.Config.OrderByDescending(t => t.Version).First();
                this.PointToMoney.Value = configDb.PointToMoney.ToString();
                this.PointToMile.Value = configDb.PointToMile.ToString();
            }
            catch
            {
                errorMessage.Visible = true;
            }
        }

        protected void btnAccept_Click(object sender, EventArgs e)
        {
            try
            {
                var db = new TopLinkEntities();

                Config objAdd = new Config();
                objAdd.PointToMoney = Convert.ToDouble(this.PointToMoney.Value.ToString());
                objAdd.PointToMile = Convert.ToDouble(this.PointToMile.Value.ToString());
                objAdd.UserID = Convert.ToInt64(Session["USERID"].ToString());
                objAdd.DateLog = DateTime.Now;

                db.AddToConfig(objAdd);
                var rs = db.SaveChanges();
                if (rs > 0)
                    Response.Redirect("/message_box.aspx?why=1&msg=4", false);
                else
                    errorMessage.Visible = true;
            }
            catch(Exception ex)
            {
                errorMessage.Visible = true;
            }
        }
    }
}